package com.specialtreasure.freightdepot.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.config.MyApp;
import com.app.core.util.CommonUtil;
import com.app.core.util.KumaToast;
import com.app.core.util.UserUtils;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.MotorCadeAdapter;
import com.specialtreasure.freightdepot.model.CUserResp;
import com.specialtreasure.freightdepot.model.MotorCade;
import com.specialtreasure.freightdepot.model.MotorCadeBean;
import com.specialtreasure.freightdepot.model.MotorCadeData;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by KUMA on 2017/9/7.
 */

public class MapActivity extends BaseNewActivity {
    public static final String TAG = "MapActivity";
    @BindView(R.id.mv_map)
    MapView mMapView;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.et_search)
    EditText etSearch;

    private BaiduMap mBaiduMap;

    List<MotorCadeBean> motorCadeDataList = new ArrayList<MotorCadeBean>();
    MotorCadeAdapter motorCadeAdapter;
    Boolean hasMode;
    Integer count = 100;//每页条数
    Integer page = 1;//页数

    BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.label3);
    Map<Marker, MotorCadeBean> map = new HashMap<>();

    private TextView tv_name;
    private TextView tv_own;
    private TextView tv_car_number;
    private TextView tv_car_height;
    private TextView tv_car_address;
    private TextView tv_car_status;
    private TextView tv_remark;
    private TextView tv_content;
    private ImageView iv_telphone;

    private int mZIndex = 10;

    @Override
    public String getActiviyName() {
        return TAG;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_map);
        ButterKnife.bind(this);
        initViews();
        initMap();
        fetchData();
    }

    private void initViews() {
        this.tv_name = (TextView) findViewById(R.id.tv_name);
        this.tv_own = (TextView) findViewById(R.id.tv_own);
        this.tv_car_number = (TextView) findViewById(R.id.tv_car_number);
        this.tv_car_height = (TextView) findViewById(R.id.tv_car_height);
        this.tv_car_address = (TextView) findViewById(R.id.tv_car_address);
        this.tv_car_status = (TextView) findViewById(R.id.tv_car_status);
        this.tv_remark = (TextView) findViewById(R.id.tv_remark);
        this.tv_content = (TextView) findViewById(R.id.tv_content);
        this.iv_telphone = (ImageView) findViewById(R.id.iv_telphone);
    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                onSelectMarker(marker);
                return false;
            }
        });
    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();
        super.onDestroy();
        bd.recycle();
    }

    public static void open(Context context) {
        Intent i = new Intent(context, MapActivity.class);
        context.startActivity(i);
    }

    private void fetchData() {
        showDialog(Constants.LOADING);
        String token = UserUtils.getToken();
        String url = Constants.HTTP_URL + HttpApi.MYCARLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", token);
        request.add("count", count);
        request.add("page", page);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                MotorCade motorCade = JSON.parseObject(result, MotorCade.class);

                if (motorCade != null) {
                    Integer status = motorCade.getStatus();
                    String msg = motorCade.getMsg();
                    //判断状态是
                    if (status != null && status == 0) {
                        MotorCadeData motorCadeData = motorCade.getData();
                        if (motorCadeData != null) {
                            hasMode = motorCadeData.getHasMore();
                            //适配数据
                            List<MotorCadeBean> motorCadetList = motorCadeData.getResultList();
                            if (motorCadetList != null && motorCadetList.size() > 0) {
                                List<Overlay> mOverlayList = new ArrayList<Overlay>();
                                for (MotorCadeBean mcb : motorCadetList) {
                                    if (mcb.getcUserResp().getcLocation() != null && mcb.getcUserResp().getcLocation().getLatitude() != null && mcb.getcUserResp().getcLocation().getLongitude() != null) {
                                        LatLng ll = new LatLng(mcb.getcUserResp().getcLocation().getLatitude(), mcb.getcUserResp().getcLocation().getLongitude());
                                        MarkerOptions mo = new MarkerOptions().position(ll).icon(bd).zIndex(mZIndex);
                                        Marker marker = (Marker) (mBaiduMap.addOverlay(mo));
                                        map.put(marker, mcb);
                                        mOverlayList.add(marker);
                                    }
                                }
                                if (mOverlayList.size() > 0) {
                                    LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                    for (Overlay overlay : mOverlayList) {
                                        // polyline 中的点可能太多，只按marker 缩放
                                        if (overlay instanceof Marker) {
                                            builder.include(((Marker) overlay).getPosition());
                                        }
                                    }
                                    mBaiduMap.setMapStatus(MapStatusUpdateFactory
                                            .newLatLngBounds(builder.build()));
                                }
                            }

                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_search:
                for (Marker k : map.keySet()) {
                    MotorCadeBean mcb = map.get(k);
                    if (mcb.getcUserResp().getUsername().equals(etSearch.getText().toString())) {
                        onSelectMarker(k);
                        return;
                    }
                }
                KumaToast.show(this, "没有查询到结果");
                break;
        }
    }

    private void onSelectMarker(Marker marker) {
        MotorCadeBean mcb = map.get(marker);
        Integer group = mcb.getGroup();
        final CUserResp cUserResp = mcb.getcUserResp();
        tv_name.setText(cUserResp.getCertName());
        if (group != null) {
            if (group == 0) {
                tv_own.setText("自有");
            } else {
                tv_own.setText("外协");
            }
        }
        tv_car_number.setText(mcb.getcUserResp().getCarNumber());
        if (cUserResp.getCarLength() != null && cUserResp.getCarType() != null) {
            tv_car_height.setText(CommonUtil.checkString(cUserResp.getCarLength()) + "/" + CommonUtil.checkString(cUserResp.getCarType()));
        } else {
            tv_car_height.setText(CommonUtil.checkString(cUserResp.getCarLength()) + CommonUtil.checkString(cUserResp.getCarType()));
        }

        if (cUserResp.getRunningRouteStart() != null && cUserResp.getRunningRoute() != null) {
            tv_car_address.setText(CommonUtil.checkString(cUserResp.getRunningRouteStart()) + "/" + CommonUtil.checkString(cUserResp.getRunningRoute()));
        } else {
            tv_car_address.setText(CommonUtil.checkString(cUserResp.getRunningRouteStart()) + CommonUtil.checkString(cUserResp.getRunningRoute()));
        }

        Integer carStatues = cUserResp.getCarStatues();//(0空车模式 1满载模式 2配货模式)
        if (carStatues != null) {
            if (carStatues == 0) {
                tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_fdb662_solid));
                tv_car_status.setText("空车");
                tv_content.setText("");
            } else if (carStatues == 1) {
                tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_bababa_solid));
                tv_car_status.setText("运输中");
                tv_content.setText("");
            } else if (carStatues == 2) {
                tv_car_status.setBackgroundDrawable(MyApp.getInstance().getResources().getDrawable(R.drawable.btn_fdb662_solid));
                tv_car_status.setText("配货");
                tv_content.setText(CommonUtil.checkString(cUserResp.getStartAddress() + "到" +
                        CommonUtil.checkString(cUserResp.getDestAddress()) + "需 , " + CommonUtil.checkString(cUserResp.getGoodsNum())));

            } else {

            }
        }
        llContent.setVisibility(View.VISIBLE);
        iv_telphone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + cUserResp.getPhone()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        marker.setToTop();
        marker.setAnimateType(2);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(marker.getPosition()));
    }
}
